<template>
  <div class="pagehead">
    <div class="title">
      <span v-if="showTitle">{{ title }}</span>
    </div>

<!--    <div class="test flex-aic">-->
<!--      <el-button @click="changeTask(-1)"> - </el-button>-->
<!--      <el-button @click="changeTask(1)"> + </el-button>-->
<!--    </div>-->

    <div class="status">
      <div class="device flex-aic">
        <div class="name">麦克风</div>
        <div class="dot" :class="{ 'connected': microphoneStatus }"></div>
      </div>
      <div class="device flex-aic">
        <div class="name">摄像头</div>
        <div class="dot" :class="{ 'connected': cameraStatus }"></div>
      </div>
      <div class="device flex-aic">
        <div class="name">手环</div>
        <div class="dot"></div>
      </div>
      <div class="device flex-aic">
        <div class="name">指夹</div>
        <div class="dot"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, onMounted, onUnmounted } from "vue";
import useTaskStore from "@/stores/task.js";
const taskStore = useTaskStore()
const changeTask = num => {
  taskStore.taskIndex += num
}

const props = defineProps({
  title: {
    type: String,
    default: '页面标题'
  },
  showTitle: {
    type: Boolean,
    default: true
  }
})

// 设备状态响应式数据
const microphoneStatus = ref(false)
const cameraStatus = ref(false)

// 检测动画帧ID
let animationFrameId = null
let lastCheckTime = 0
const CHECK_INTERVAL = 5000 // 5秒检测一次

/**
 * 检测麦克风状态
 */
const checkMicrophoneStatus = async () => {
  try {
    const devices = await navigator.mediaDevices.enumerateDevices()
    const audioInputDevices = devices.filter(device => device.kind === 'audioinput')

    if (audioInputDevices.length > 0) {
      // 尝试获取麦克风权限来确认设备可用
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
      microphoneStatus.value = true
      // 立即停止流以释放资源
      stream.getTracks().forEach(track => track.stop())
    } else {
      microphoneStatus.value = false
    }
  } catch (error) {
    console.warn('麦克风检测失败:', error)
    microphoneStatus.value = false
  }
}

/**
 * 检测摄像头状态
 */
const checkCameraStatus = async () => {
  try {
    const devices = await navigator.mediaDevices.enumerateDevices()
    const videoInputDevices = devices.filter(device => device.kind === 'videoinput')

    if (videoInputDevices.length > 0) {
      // 尝试获取摄像头权限来确认设备可用
      const stream = await navigator.mediaDevices.getUserMedia({ video: true })
      cameraStatus.value = true
      // 立即停止流以释放资源
      stream.getTracks().forEach(track => track.stop())
    } else {
      cameraStatus.value = false
    }
  } catch (error) {
    console.warn('摄像头检测失败:', error)
    cameraStatus.value = false
  }
}

/**
 * 检测所有设备状态
 */
const checkDeviceStatus = async () => {
  await Promise.all([
    checkMicrophoneStatus(),
    checkCameraStatus()
  ])
}

/**
 * 使用requestAnimationFrame进行实时监测
 */
const startDeviceMonitoring = () => {
  const monitor = (currentTime) => {
    // 每5秒检测一次设备状态
    if (currentTime - lastCheckTime >= CHECK_INTERVAL) {
      checkDeviceStatus()
      lastCheckTime = currentTime
    }

    // 继续下一帧监测
    animationFrameId = requestAnimationFrame(monitor)
  }

  // 开始监测
  animationFrameId = requestAnimationFrame(monitor)
}

/**
 * 停止设备监测
 */
const stopDeviceMonitoring = () => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }
}

/**
 * 监听设备变化
 */
const handleDeviceChange = () => {
  checkDeviceStatus()
}

onMounted(() => {
  // 初始检测
  checkDeviceStatus()

  // 监听设备变化事件
  navigator.mediaDevices.addEventListener('devicechange', handleDeviceChange)

  // 使用requestAnimationFrame开始实时监测
  startDeviceMonitoring()
})

onUnmounted(() => {
  // 清理监听器和动画帧
  if (navigator.mediaDevices) {
    navigator.mediaDevices.removeEventListener('devicechange', handleDeviceChange)
  }
  stopDeviceMonitoring()
})
</script>

<style scoped lang="scss">

.pagehead{
  width: 100%;
  height: .8rem;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #fff;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 999;
  background: #000000;
  .title{
    span{
      font-size: 24px;
    }
  }
  .status{
    display: flex;
    align-items: center;

    .device{
      margin-right: 24px;
      .dot{
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: #FE6057;
        margin-left: 14px;
        transition: background-color 0.3s ease;

        &.connected {
          background: #52C41A;
        }
      }
    }
  }
}
</style>
